package activities;






import io.fabric.sdk.android.Fabric;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Date;

import persistencia.BaseDatos;


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.androidmodule.onthego.R;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.OpenGraphAction;
import com.facebook.model.OpenGraphObject;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.FacebookDialog.OpenGraphActionDialogBuilder;



import entidades.Reserva;
import extras.Fonts;
import extras.GCM;
import extras.NetInfo;
import extras.Utilities;
import extras.leerPreferencias;

public class MainActivity  extends ActionBarActivity{
	// Note: Your consumer key and secret should be obfuscated in your source code before shipping.

	private static final String TWITTER_KEY = "9AmQNRAYQVa5Db4Ya3Gz2Q";

	private static final String TWITTER_SECRET = " lhWr8XnLtdjrQp2m0Tht3n3EZqNdYjLpbcWjSodfM";

	

	static final String TAG = "FACEBOOK";

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private UiLifecycleHelper uiHelper;

	public void onCreate(Bundle savedInstanceState){
	    super.onCreate(savedInstanceState);
		//TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
		//Fabric.with(this, new TweetComposer());
       setContentView(R.layout.layout_main_activity);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        mTitle = mDrawerTitle = getTitle();

        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);
        
        if(leerPreferencias.readPrimeraVez(getApplicationContext())){
        	if(NetInfo.isOnline(getApplicationContext())){
        		if(NetInfo.conectadoAWIFI(getApplicationContext())){
        			GCM gcm = new GCM(getApplicationContext());
        			gcm.ValidarRed();
        		
        		}
        		else{
        			leerPreferencias.writeConexionValida(getApplicationContext(), false);
        		}
        	}
        	else{
        		leerPreferencias.writeConexionValida(getApplicationContext(), false);
        	}
        	
        	leerPreferencias.writePrimeraVez(getApplicationContext(), false);
        }
        
        Button promocionComunes = (Button)findViewById(R.id.btn_Promocion_Comun);
        Button promocionHot = (Button)findViewById(R.id.btn_Promocion_Hot);
        Button centrosComerciales = (Button)findViewById(R.id.btn_CentroComercial);
        Button btnReservas = (Button) findViewById(R.id.btn_Reservas);
        Button comerciosAdheridos = (Button) findViewById(R.id.btn_ComerciosAdheridos);
        Button btnSettings = (Button) findViewById(R.id.btn_settings);
        //LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
        //authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));
        
        promocionComunes.setOnClickListener(new OnClickListener (){

			@Override
			public void onClick(View arg0) {
			
				Intent intento = new Intent(getApplicationContext(),ActivityPromocionesComunes.class);
				startActivity(intento);
				   
			 
	
				
			}
        });
        promocionComunes.setTypeface(Fonts.mvboli(getApplicationContext()));
        promocionHot.setOnClickListener(new OnClickListener (){

			@Override
			public void onClick(View arg0) {
				Intent intento = new Intent(getApplicationContext(),ActivityPromocionesHot.class);
				startActivity(intento);
			}
        });
        promocionHot.setTypeface(Fonts.mvboli(getApplicationContext()));
        centrosComerciales.setOnClickListener(new OnClickListener (){

			@Override
			public void onClick(View arg0) {
				if(NetInfo.isOnline(getApplicationContext())){
				Intent intento = new Intent (getApplicationContext(), ActivityCentrosComerciales.class);
				startActivity(intento); 
				}
				else{
					Utilities.makeToastLong(getApplicationContext(), getString(R.string.lista_sinConexion));
				}
			}
        });
        centrosComerciales.setTypeface(Fonts.mvboli(getApplicationContext()));
        btnReservas.setOnClickListener(new OnClickListener (){

			@Override
			public void onClick(View arg0) {
				Intent intento = new Intent (getApplicationContext(), ActivityReservas.class);
				startActivity(intento);
				
				
			}
        });
        btnReservas.setTypeface(Fonts.mvboli(getApplicationContext()));
        comerciosAdheridos.setOnClickListener(new OnClickListener (){

			@Override
			public void onClick(View arg0) {
				Intent intento = new Intent(getApplicationContext(),ActivityComerciosAdheridos.class);
				intento.putExtra("CentroComercialId", -1);
				startActivity(intento);
			}
        });
        comerciosAdheridos.setTypeface(Fonts.mvboli(getApplicationContext()));
        btnSettings.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				 Intent intentoActivity = new 
				 Intent(MainActivity.this,ActivityPreferenciasGenerales.class);
			     startActivity(intentoActivity);
				
			}});
        btnSettings.setTypeface(Fonts.mvboli(getApplicationContext()));
        
        NetInfo info = new NetInfo(this);
     
      //Toast.makeText(getApplicationContext(),info.getBSSID() , Toast.LENGTH_LONG).show();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu_pagina_principal,menu);
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_principal_opciones:
	            Intent intentoActivity = new 
				Intent(getApplicationContext(),ActivityPreferenciasGenerales.class);
		        startActivity(intentoActivity);
	        return true;

	        case android.R.id.home:
	            // app icon in action bar clicked; go home
	        	// comprtamiento por defeto de android si se clikea icono en action bar activa android.R.id.home
	            Intent intent = new Intent(this, ActivityPromocionesComunes.class);// cambiar por la que sea home
	            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            startActivity(intent);
	            return true;
	            // NO ANDA VER PORQUE
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
    protected void onResume(){
    	super.onResume();
    	uiHelper.onResume();
    }
    protected void onPause(){
    	super.onPause();
    	uiHelper.onPause();
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
            @Override
            public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
                Log.e("Activity", String.format("Error: %s", error.toString()));
                error.printStackTrace();
            }

            @Override
            public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
                Log.i("Activity", "Success!");
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }

	
	

/********************************************METODOS PARA FACEBOOK*************************************/
	
	
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
	    if (state.isOpened()) {
	        Log.i(TAG, "Logged in...");
	    } else if (state.isClosed()) {
	        Log.i(TAG, "Logged out...");
	    }
	}
	
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(Session session, SessionState state, Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	private void publicarHistoria(){
	 /*
		OpenGraphObject recipe = OpenGraphObject.Factory.createForPost("OnTheGo");
		recipe.setDescription("DESCRIPCION");
		recipe.setTitle("TITULO");
		
		Bitmap imagen = BitmapFactory.decodeResource(getResources(), R.drawable.shopping);
		List<Bitmap> images = new ArrayList<Bitmap>();
		images.add(imagen);

		OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
		action.setProperty("route", recipe);

		FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "fbsdktoolkit:climb", "route")
		   // .setImageAttachmentsForObject("route", images, true)
		    .build();
		uiHelper.trackPendingDialogCall(shareDialog.present());
		*/
	
	}
/***************************************************************************************************/

	
	/**
	 * Este hilo se lanza cuando se inicia la aplicacion y lo que hace es eliminar reservas, que hayan 
	 * qeudado guardadas por una posile falla en el hilo
	 */
	
	public void eliminarReservas(){
    	new AsyncTask<Void, Void, Void>() {
           

                @Override
                protected Void doInBackground(Void... params) { 
                	BaseDatos base = new BaseDatos(getApplicationContext());
                	ArrayList<Reserva> reservas = base.getReservas();
                	
                	for(Reserva reserva:reservas){
                		// si la hora fin de la reserva guardada, es menor a la fecha actual la elimino
                	if(reserva.getHoraFin()!=null	){
                		if(Utilities.getDateFromString(reserva.getHoraFin()).before(new Date())){
                			base.eliminarReserva(reserva.getCodigo());
                			
                		}
                	}
                	}
                	
                     return null;
                }


             
        }.execute();
    }
	
	
	//////////////
	
	public void publicarOnFace(){
		
		if (FacebookDialog.canPresentShareDialog(getApplicationContext(), 
                FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
			
			
			OpenGraphObject prom = OpenGraphObject.Factory.createForPost("onthegost:promotion");
			prom.setProperty("title", "OnTheGo");
			//prom.setProperty("image", "http://example.com/cooking-app/images/buffalo-tacos.png");
			//prom.setProperty("url", "https://example.com/cooking-app/meal/Buffalo-Tacos.html");
			prom.setProperty("description", "Probando integracion con redes sociales");
			
			OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
			action.setProperty("promotion", prom);
			action.setType("onthegost:book");
			
			//FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "onthegost:book", "onthegost:promotion")
			FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "promotion")
			.build();


           uiHelper.trackPendingDialogCall(shareDialog.present());

} else {
	
}
	}
}
